import axios, { AxiosInstance } from "axios"
import { AxiosRequest } from "./types"
import CCLoading from "@/utils/http/loading"
import router from "@/router"
import { ElMessage } from "element-plus"

const ccLoading = new CCLoading()

class HTTP {
  instance: AxiosInstance
  requestNum: number = 0
  constructor() {
    this.instance = axios.create({
      // baseURL: "/mock/",
      baseURL: "/api/",
      timeout: 1000 * 60,
    })
    this.interceptRequest()
    this.interceptResponse()
  }

  request(params: AxiosRequest) {
    if (params.formdata) {
      // 兼容参数params 和data
      params.data = this.json2formdata(params.data || params.params)
      if (params.params) delete params.params
      delete params.formdata
    }
    return this.instance(params)
  }

  json2formdata(params: { [x: string]: string | Blob }): string {
    let query: string = ""
    if (Object.prototype.toString.call(params) === "[object Object]") {
      for (const KEY in params) {
        if (Object.prototype.hasOwnProperty.call(params, KEY)) {
          query += `${KEY}=${params[KEY]}&`
        }
      }
    }
    return query
  }

  interceptRequest() {
    this.instance.interceptors.request.use((request: any) => {
      const token = window.localStorage.getItem("token") || ""
      const useLoginStore =
        JSON.parse(window.sessionStorage.getItem("useLoginStore")) || ""

      if (request.url !== "ucenter/login") {
        request.headers["token"] = token
        request.headers["enterpriseId"] = useLoginStore.nowEnterpriseId
      } else {
        //登陆是否加密
        if (window.GLOBALADDRESS.special) {
          request.headers["special"] = !!window.GLOBALADDRESS.special
        }
      }
      if (request.url.includes("/upload/")) {
        request.baseURL = ""
      }
      if (request.openResponese) {
        request.responseType = "arraybuffer"
      }
      if (!request.hideLoading) {
        //是否隐藏loading
        this.requestNum++
        // ccLoading.show()
      }
      return request
    })
  }

  interceptResponse() {
    this.instance.interceptors.response.use(
      (response: any) => {
        let responseVal = response?.data ?? {}
        if (!response.config.hideLoading) {
          //是否隐藏loading
          this.requestNum--
        }
        if (!this.requestNum) {
          // ccLoading.hide()
        }
        if (response.config.openResponese) {
          //文件流下载
          return response.data
        }

        if (response.status === 200 && response.data.errno === 0) {
          if (response.config.openResponese) {
            responseVal = response?.data ?? {}
          }
          return responseVal
        } else {
          if (response.data.errno === 9101) {
            this.requestNum--
            if (this.requestNum === -1 || this.requestNum === -2) {
              ElMessage({
                message: response.data.errmsg,
                type: "error",
              })
            }
            //登录过期回到登录页
            this.backLoginPage()
            return response.data
          }
          if (
            !response.request.responseURL.includes("api/activity/sceneSign")
          ) {
            ElMessage({
              message: response.data.errmsg,
              type: "error",
            })
          }
          // alert(response.data.errmsg)
          // ElMessage.error(response.data.errmsg)
          this.requestNum = 0
          // ccLoading.hide()
          return response.data
          // return Promise.reject(response.data.errmsg)
        }
      },
      (error) => {
        //请求出错
        this.requestNum--
        if (Object.prototype.toString.call(error) === "[object Error]") {
          ElMessage.error("网络繁忙")
        } else {
          ElMessage.error(JSON.stringify(error))
        }
        if (!this.requestNum) {
          ccLoading.hide()
        }
        return Promise.reject(error.response)
      }
    )
  }

  backLoginPage() {
    router.push({
      path: "/login",
    })
  }
}

export default HTTP
